<template>
  <div class="contarct-form">
   <el-form
      ref="contarctForm"
      :model="formData"
      label-width="100px"
      :rules="rules"
      :disabled="$route.query.readonly ? true : false"
      v-if="visible"
    >
      <el-row v-for="(item, index) in rows" :key="index">
        <el-col v-for="col in item" :span="24" :key="col.name">
          <!-- parameterType 1 文本,2 数字,3 单选,4 复选,5 日期和时间,6 文本域,7 附件,8 主数据,9 非标准 -->
          <el-form-item :label="col.parameterName" :prop="col.name"  :key="col.ruleFieldKey">
            <template v-if="col.parameterType == 1">
              <el-input
                v-model="formData[col.name]"
                :maxlength="col.parameterValue.textLimit"
                show-word-limit
                :disabled="col.state === 2"
                :placeholder="col.promptTemplate||'请输入'"
                @blur="changeRule(col)"
              ></el-input>
            </template>
            <!-- 数字 -->
            <template v-if="col.parameterType == 2">
              <el-input
                v-model="formData[col.name]"
                maxlength="21"
                :disabled="col.state === 2"
                :placeholder="col.promptTemplate||'请输入'"
                @blur="changeRule(col)"
              ></el-input>
            </template>
            <!-- 单选、多选 -->
            <template v-if="col.parameterType == 3 || col.parameterType == 4">
              <el-row>
                <el-col :span="24">
                  <!-- 关联数据 -->
                  <template v-if="col.parameterValue.enumType == 2">
                    <dataSource
                      v-model="formData[col.name]"
                      :ref="col.parameterNumber"
                      :disabled="col.state === 2"
                      :parameter="col"
                      :detail="detail"
                      :current-form="formData"
                      @setrules="setRules"
                      @changeRule="changeRule(col)"
                    ></dataSource>
                  </template>
                  <template v-else>
                    <el-select
                      v-model="formData[col.name]"
                      :disabled="col.state === 2"
                      :multiple="col.parameterType === 4"
                      :placeholder="col.promptTemplate||'请选择'"
                      clearable
                      @change="(arg) => changeSelect(arg, col)"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="option in col.parameterValue.optionsStr"
                        :key="option.optionName"
                        :label="option.optionDesc || option.optionName"
                        :value="option.optionName"
                      ></el-option>
                    </el-select>
                  </template>
                </el-col>
                <el-col :span="12">
                  <template v-if="pageType === 'template'">
                    <template
                      v-if="
                        col.ruleList &&
                        col.ruleList.length &&
                        col.ruleList.filter((it) => it.conditionType == 2)
                          .length
                      "
                    >
                      <el-badge
                        :value="
                          col.ruleList.filter((it) => it.conditionType == 2)
                            .length
                        "
                        class="item"
                      >
                        <el-button
                          type="text"
                          style="margin-left: 10px"
                          @click="changeCondition(col, 1)"
                          >{{ $t('条件默认值') }}</el-button
                        >
                      </el-badge>
                    </template>
                    <el-button
                      v-else
                      type="text"
                      style="margin-left: 10px"
                      @click="changeCondition(col, 1)"
                      >{{ $t('条件默认值') }}</el-button
                    >
                    <template
                      v-if="
                        col.ruleList &&
                        col.ruleList.length &&
                        col.ruleList.filter((it) => it.conditionType == 3)
                          .length
                      "
                    >
                      <el-badge
                        :value="
                          col.ruleList.filter((it) => it.conditionType == 3)
                            .length
                        "
                        class="item"
                      >
                        <el-button
                          type="text"
                          style="margin-left: 10px"
                          @click="changeCondition(col, 2)"
                          >{{ $t('条件选项') }}</el-button
                        >
                      </el-badge>
                    </template>
                    <el-button
                      v-else
                      type="text"
                      @click="changeCondition(col, 2)"
                      >{{ $t('条件选项') }}</el-button
                    >
                  </template>
                </el-col>
              </el-row>
            </template>
            <!-- 时间 -->
            <template v-if="col.parameterType === 5">
              <el-date-picker
              v-model="formData[col.name]" 
              :disabled="col.state === 2"
              :type="col.parameterValue.dateType"
              :format="col.parameterValue.format"
              :value-format="col.parameterValue.valueFormat"
              :range-separator="col.parameterValue.rangeSeparator"
              :start-placeholder="col.parameterValue.startPlaceholder"
              :end-placeholder="col.parameterValue.endPlaceholder"
              :placeholder="col.promptTemplate||'请选择'"
              @change="arg => changeTime(arg, col)"
              >
              </el-date-picker>
            </template>
            <!-- 文本域 -->
            <template v-if="col.parameterType === 6">
              <el-input 
              v-model="formData[col.name]"
              type="textarea" 
              :maxlength="col.parameterValue.textLimit" 
              show-word-limit
              :disabled="col.state === 2"
              :rows="6"
              :placeholder="col.promptTemplate"
              @blur="changeRule(col)"
              ></el-input>
            </template>
            <!-- 附件 -->
            <template v-if="col.parameterType === 7">
              <file 
              :ref="col.parameterNumber"
              v-if="col.parameterNumber"
              v-model="formData[col.name]"
              :parameter="col"
              :disabled="col.state === 2" 
              :detail="detail"
              :pageType="pageType"
              :definitionId='definitionId'
              :current-form="formData"
              ></file>
            </template>
            <!-- 主数据 -->
            <template v-if="['signTarget','signSubject'].includes(col.parameterNumber) && col.parameterType === 9">
              <masterData 
              v-model="formData[col.name]" 
              :ref="col.parameterNumber"
              :disabled="col.state === 2" 
              :parameter="col"
              :detail="detail"
              :current-form="formData"
              @setrules="setRules"
              ></masterData>
            </template>
            <!-- 非标准 -->
            <template v-else-if="col.parameterType === 9">
              <component 
              :ref="col.parameterNumber"
              :is="col.parameterNumber"
              v-if="col.parameterNumber"
              v-model="formData[col.name]"
              :parameter="col"
              :disabled="col.state === 2" 
              :detail="detail"
              :rows="rows"
              :pageType="pageType"
              @changeData="changeData"
              :definitionId='definitionId'
              :current-form="formData"
              @setrules="setRules"
              ></component>
            </template>
            <!-- 选人 -->
            <template v-if="col.parameterType === 10">
              <userComponent 
              v-model="formData[col.name]" 
              :ref="col.parameterNumber"
              :disabled="col.state === 2" 
              :parameter="col"
              :detail="detail"
              :current-form="formData"
              @setrules="setRules"
              @changeRule="changeRule(col)"
              ></userComponent>
            </template>
            <!-- 地区 -->
            <template v-if="col.parameterType === 11">
              <areaSelected 
              v-model="formData[col.name]" 
              :ref="col.parameterNumber"
              :disabled="col.state === 2" 
              :parameter="col"
              :detail="detail"
              :current-form="formData"
              @setrules="setRules"
              @changeRule="changeRule(col)"
              ></areaSelected>
            </template>
            <!-- 选电子文本 -->
            <template v-if="col.parameterType === 12">
              <electronicText 
              v-model="formData[col.name]" 
              :ref="col.parameterNumber"
              :disabled="col.state === 2" 
              :parameter="col"
              :detail="detail"
              :current-form="formData"
              @setrules="setRules"
              @changeRule="changeRule(col)"
              ></electronicText>
            </template>
            <!-- 号码类 -->
            <template v-if="col.parameterType === 13">
              <el-input
                v-model="formData[col.name]"
                :disabled="col.state === 2"
                :placeholder="col.promptTemplate"
                @blur="changeRule(col)"
              ></el-input>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import Vue from 'vue'
import contractCreationService from '@/services/contractCreationService'
import eventBus from '@/assets/utils/eventBus.js'
import file from './nonStandard/files'
import masterData from './masterData'
import nonStandardCom from './nonStandard'
import parkNonStandardCom from './parkNonStandard'
import projectNonStandard from "./projectNonStandard";
import parkProjectNonStandard from "./parkProjectNonStandard";
// 选人组件
import userComponent from '@/views/personalCenter/components/controlType/userComponent.vue'
// 关联数据
import dataSource from '@/views/personalCenter/components/controlType/dataSource.vue'
// 选电子文本
import electronicText from '@/views/personalCenter/components/controlType/electronicText.vue'
// 设置选项默认值
import setDefaultValue from '@/views/personalCenter/components/setCondition/setDefaultValue.vue'
// 设置可选选项
import setOption from '@/views/personalCenter/components/setCondition/setOption.vue'
//动态加载非标准组件
nonStandardCom.forEach((it) => {
  Vue.component(it.name, it)
})
parkNonStandardCom.forEach((it) => {
  Vue.component(it.name, it)
})
projectNonStandard.forEach((it) => {
  Vue.component(it.name, it);
});
parkProjectNonStandard.forEach((it) => {
  Vue.component(it.name, it);
});

export default {
  components: { file, masterData, userComponent, dataSource, electronicText, setDefaultValue, setOption },
  props: {
    list: {
      type: Array,
      default: () => {
        return []
      }
    },
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    cols: {
      type: Number,
      default: 2
    },
    pageType: {
      type: String,
      default: ''
    },
    definitionId: {},
    rowData: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  watch: {
    list: { 
      handler(newVal, oldVal) { 
        if(newVal.length) {
          this.resetData();
        }
      },
      deep: true
    }
  },
  data() {
    return {
      rows: [],
      rules: {},
      nonStandardCom: '',
      originList: [],
      visible: false,
      row: {},
      defaultValueVisible: false,
      optionVisible: false,
    }
  },
  computed: {
    formData: {
      get() {
        return this.$store.state.contract.headerForm
      },
      set(value) {
        this.$store.dispatch('contract/setHeaderForm', value)
      },
    },
  },
  created() {
    this.resetData()
  },
  methods: {
    resetData() {
      let vm = this
      let cellCols = 24 / this.cols
      let list = this.list
        .filter((it) => {
          return it.state !== 1 //排除隐藏的字段，1-隐藏 2-仅显示 3-选填 4-必填
        })
        .map((it) => {
          let obj = {
            ...it,
            name: it.parameterNumber,
            innerSpan: [
              'workVoucherInfoList',
              'otherExpenses',
              'UsualLine',
            ].includes(it.parameterNumber)
              ? 24
              : cellCols,
            parameterValue: it.parameterValueStr
              ? JSON.parse(it.parameterValueStr)
              : {},
          }
          //  timeCount 1-单项 2-双项 timeType:1-日期 2-时间:
          if (obj.parameterType === 5) {
            let dateType = 'date'
            let format = 'yyyy-MM-dd'
            let valueFormat = 'yyyy-MM-dd'
            let rangeSeparator = null
            let startPlaceholder = null
            let endPlaceholder = null
            if (
              obj.parameterValue.timeCount === 1 &&
              obj.parameterValue.timeType === 1
            ) {
              dateType = 'date'
            }
            if (
              obj.parameterValue.timeCount === 1 &&
              obj.parameterValue.timeType === 2
            ) {
              dateType = 'datetime'
              format = 'yyyy-MM-dd HH:mm:ss'
              valueFormat = 'yyyy-MM-dd HH:mm:ss'
            }
            if (
              obj.parameterValue.timeCount === 2 &&
              obj.parameterValue.timeType === 1
            ) {
              dateType = 'daterange'
              format = 'yyyy-MM-dd'
              valueFormat = 'yyyy-MM-dd'
              rangeSeparator = this.$t('至')
              startPlaceholder = this.$t('开始日期')
              endPlaceholder = this.$t('截止日期')
            }
            if (
              obj.parameterValue.timeCount === 2 &&
              obj.parameterValue.timeType === 2
            ) {
              dateType = 'datetimerange'
              format = 'yyyy-MM-dd HH:mm:ss'
              valueFormat = 'yyyy-MM-dd HH:mm:ss'
              rangeSeparator = this.$t('至')
              startPlaceholder = this.$t('开始时间')
              endPlaceholder = this.$t('截止时间')
            }
            obj.parameterValue = {
              ...obj.parameterValue,
              optionsStr: obj.parameterValue.optionsStr || [],
              dateType: dateType,
              format: format,
              valueFormat: valueFormat,
              rangeSeparator: rangeSeparator,
              startPlaceholder: startPlaceholder,
              endPlaceholder: endPlaceholder,
            }
          }
          if (it.defaultValue) {
            vm.$set(vm.formData, it.parameterNumber, it.defaultValue)
          }
          if (
            obj.parameterValue.timeCount == 2 &&
            this.formData[it.parameterNumber]
          ) {
            if (it.defaultValue) {
              if (typeof it.defaultValue == 'string') {
                vm.$set(
                  vm.formData,
                  it.parameterNumber,
                  it.defaultValue.split(',')
                )
              } else {
                vm.$set(vm.formData, it.parameterNumber, it.defaultValue)
              }
            }
          }
          vm.setRules(obj)
          return obj
        })
      this.originList = list //将处理后的数组赋给originList
      vm.rows = list.reduce((prev, next, index, arr) => {
        if (index % vm.cols === 0) {
          prev.push([])
        }
        prev[prev.length - 1].push(next)
        return prev
      }, [])
      this.visible = true
      // this.$refs.contarctForm.clearValidate();
    },
    setRules(parameter, rules) {
      let vm = this
      if (rules) {
        this.rules = {
          ...this.rules,
          ...rules,
        }
      } else if (parameter.parameterType === 2) {
        const rules = [
          {
            required: parameter.state === 4,
            validator: (rule, value, callback) => {
              let reg = null
              if (
                parameter.parameterValue.decimalLimit ||
                parameter.parameterValue.decimalLimit == 0
              ) {
                reg = new RegExp(
                  `^(-)*([0-9]{1,${parameter.parameterValue.integerLimit}})(\\.[0-9]{0,${parameter.parameterValue.decimalLimit}})?$`
                )
              } else {
                reg = new RegExp(
                  `^(-)*([0-9]{1,${parameter.parameterValue.integerLimit}})(\\.[0-9]{0,8})?$`
                )
              }
              let maxValue = parameter.parameterValue.maxValue
                ? parameter.parameterValue.maxValue
                : null
              let minValue = parameter.parameterValue.minValue
                ? parameter.parameterValue.minValue
                : null
              let decimalLimit =
                parameter.parameterValue.decimalLimit ||
                parameter.parameterValue.decimalLimit == 0
                  ? parameter.parameterValue.decimalLimit
                  : 8
              if (parameter.state === 4) {
                if (!value) {
                  callback(
                    new Error(parameter.parameterName + this.$t('是必填项'))
                  )
                } else if (!reg.test(value)) {
                  callback(
                    new Error(
                      this.$t('只能输入整数最多') +
                        parameter.parameterValue.integerLimit +
                        this.$t('位,小数') +
                        decimalLimit +
                        this.$t('位')
                    )
                  )
                } else if (
                  (maxValue && Number(value) > maxValue) ||
                  (minValue && Number(value) < minValue)
                ) {
                  if (maxValue && Number(value) > maxValue) {
                    callback(
                      new Error(
                        this.$t('请输入比') + maxValue + this.$t('小的值')
                      )
                    )
                  }
                  if (minValue && Number(value) < minValue) {
                    callback(
                      new Error(
                        this.$t('请输入比') + minValue + this.$t('大的值')
                      )
                    )
                  }
                } else {
                  callback()
                }
              } else {
                if (value && !reg.test(value)) {
                  callback(
                    new Error(
                      this.$t('只能输入整数最多') +
                        parameter.parameterValue.integerLimit +
                        this.$t('位,小数') +
                        decimalLimit +
                        this.$t('位')
                    )
                  )
                } else if (
                  value &&
                  ((maxValue && Number(value) > maxValue) ||
                    (minValue && Number(value) < minValue))
                ) {
                  if (maxValue && Number(value) > maxValue) {
                    callback(
                      new Error(
                        this.$t('请输入比') + maxValue + this.$t('小的值')
                      )
                    )
                  }
                  if (minValue && Number(value) < minValue) {
                    callback(
                      new Error(
                        this.$t('请输入比') + minValue + this.$t('大的值')
                      )
                    )
                  }
                } else {
                  callback()
                }
              }
            },
            trigger: ['blur', 'change'],
          },
        ]
        this.$set(this.rules, parameter.name, rules);
      } else if (parameter.parameterType === 13) {
        const rules = [
          {
            required: parameter.state === 4,
            validator: (rule, value, callback) => {
              let reg = null
              let errMsg = ''
              // 手机号
              if (parameter.parameterValue.numberType == 1) {
                reg = /^1\d{10}$/
                errMsg = this.$t('请输入正确的手机号')
              } else if (parameter.parameterValue.numberType == 2) {
                // 身份证号
                reg =
                  /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/
                errMsg = this.$t('请输入正确的身份证号')
              }
              if (parameter.state === 4) {
                if (!value) {
                  callback(
                    new Error(parameter.parameterName + this.$t('是必填项'))
                  )
                } else if (!reg.test(value)) {
                  callback(new Error(errMsg))
                } else {
                  callback()
                }
              } else {
                if (value && !reg.test(value)) {
                  callback(new Error(errMsg))
                } else {
                  callback()
                }
              }
            },
            trigger: ['blur', 'change'],
          },
        ]
        this.$set(this.rules, parameter.name, rules);
      } else {
        let type = 'string'
        if (
          (parameter.parameterType === 5 &&
          parameter.parameterValue.timeCount == 2) || parameter.parameterType === 4
        ) {
          type = 'array'
        }
        if (parameter.parameterType === 8) {
          type = 'object'
        }
        if (
          ['workVoucherInfoList', 'otherExpenses', 'UsualLine'].includes(
            parameter.parameterNumber
          )
        ) {
          type = 'array'
        }
        const rules = [
          {
            required: parameter.state === 4,
            message: parameter.parameterName + this.$t('是必填项'),
            trigger: ['blur', 'change'],
            type: type,
          },
        ]
        this.$set(this.rules, parameter.name, rules);
      }
    },
    // 下拉选择
    changeSelect(val, col) {
      if (col.name == 'rentPayType') {
        eventBus.$emit('rentPayTypeChange', val)
      }
      this.changeRule(col)
    },
    // 时间选择
    changeTime(val, col) {
      if (col.name == 'startEndTime') {
        eventBus.$emit('startEndTimeChange', val)
        localStorage.setItem('startEndTime', JSON.stringify(val))
      }
      this.changeRule(col)
    },
    changeCondition(row, type) {
      this.row = {
        ...row,
        templateTypeCode: this.detail.templateTypeCode,
        pageName: row.projectDetailTitle || '抬头信息',
      }
      if (type == 1) {
        this.defaultValueVisible = true
      }
      if (type == 2) {
        this.optionVisible = true
      }
    },
    // 设置选项默认值
    setDefaultValue(data) {
      // 设置字段默认值
      this.rows = (this.rows || []).map((it) => {
        ;(it || []).map((item) => {
          if (item.parameterNumber === this.row.parameterNumber) {
            item.ruleList = data
          }
        })
        return it
      })
      // 设置字段数据默认值
      this.originList = (this.originList || []).map((it) => {
        if (it.parameterNumber === this.row.parameterNumber) {
          it.ruleList = data
        }
        return {
          ...it,
        }
      })
    },
    // 设置可选选项
    setOption(data) {
      // 设置字段默认值
      this.rows = (this.rows || []).map((it) => {
        ;(it || []).map((item) => {
          if (item.parameterNumber === this.row.parameterNumber) {
            item.ruleList = data
          }
        })
        return it
      })
      // 设置字段数据默认值
      this.originList = (this.originList || []).map((it) => {
        if (it.parameterNumber === this.row.parameterNumber) {
          it.ruleList = data
        }
        return {
          ...it,
        }
      })
    },
    changeRule(row) {
      if (!(row.relatedRuleFieldList && row.relatedRuleFieldList.length)) {
        return
      }
      this.$emit('changeRule', row)
    },
    getArrData() {
      const vm = this
      let parameterList = vm.originList.map((it) => {
        let headerValue =
          typeof vm.formData[it.name] == 'string'
            ? vm.formData[it.name]
            : JSON.stringify(vm.formData[it.name])
        // 双项时间选择器,将数组转成字符串
        if (
          it.parameterValue.timeCount == 2 &&
          this.formData[it.parameterNumber] instanceof Array
        ) {
          console.log(
            this.formData[it.parameterNumber],
            'this.formData[it.parameterNumber]this.formData[it.parameterNumber]'
          )
          let obj = { value: this.formData[it.parameterNumber] }
          console.log(obj, 'sssssssssssss')
          headerValue = JSON.stringify(obj)
        }
        //对附件、主数据组件做特殊处理
        if ([7, 8, 9].includes(it.parameterType)) {
          let obj = vm.$refs[it.parameterNumber][0].getData()
          headerValue = obj ? JSON.stringify(obj) : null
        }
        // 对作业凭证、其它费用
        if (
          ['workVoucherInfoList', 'otherExpenses', 'UsualLine'].includes(
            it.parameterNumber
          )
        ) {
          let arr =
            vm.$refs[it.parameterNumber][0].getData() ||
            this.formData[it.parameterNumber]
          headerValue = JSON.stringify(arr)
        }
        return {
          ...it,
          headerValue,
        }
      })
      return parameterList
    },
    getData() {
      let vm = this
      let def = []
      if (this.$refs.workVoucherInfoList) {
        def.push(vm.$refs.workVoucherInfoList[0].validator())
      }
      // if(this.$refs.otherExpenses) {
      //     def.push(vm.$refs.otherExpenses[0].validator())
      // }
      return Promise.all(def).then(() => {
        return new Promise((resolve, reject) => {
          vm.$refs.contarctForm
            .validate()
            .then(() => {
              let parameterList = (this.getArrData() || []).map((it) => {
                return {
                  parameterNumber: it.parameterNumber,
                  parameterId: it.parameterId,
                  headerValue: it.headerValue,
                  ruleList: it.ruleList,
                  parameterType: it.parameterType,
                }
              })
              console.log(parameterList, 'parameterList')
              resolve(parameterList)
            })
            .catch(() => {
              reject(undefined)
            })
        })
      })
    },
    validator() {
      return this.$refs.contarctForm.validate()
    },
    // 非标选择数据，数据渲染
    changeData(data) {
      this.$set(this.formData, data.parameterNumber, String(data.value))
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-badge {
  margin-right: 10px;
}
::v-deep .el-button--text {
  line-height: 15px;
}
</style>
